export class Particle{
    constructor(x, y, option = {}){
        let colors = [
            '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
            '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
            '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
            '#FF5722'
        ]
        const {radVal = 2, graVal, durVal, spdVal, ctx} = option
        this.x = x
        this.y = y
        this.radius = 1.1
        this.futurRadius = Math.random() * 3 + radVal
        this.rebond = Math.random() * 4 + 1
        this.dying = false
        this.base = [x, y]
        this.vx = 0
        this.vy = 0
        this.friction = 0.99
        this.graVal = graVal
        this.ctx = ctx
        this.radVal = radVal
        this.durVal = durVal
        this.spdVal = spdVal
        this.color = colors[parseInt(Math.random() * colors.length)]
        this.setSpeed(Math.random() * 0.4 + 0.1)
        this.setHeading(Math.random() * 360 / 180 * Math.PI)
    }
    getSpeed(){
        return Math.sqrt(this.vx * this.vx + this.vy * this.vy)
    }
    getHeading(){
        return Math.atan2(this.vy, this.vx)
    }
    setSpeed(speed){
        const heading = this.getHeading()
        this.vx = Math.cos(heading) * speed
        this.vy = Math.sin(heading) * speed
    }
    setHeading(heading){
        const speed = this.getSpeed()
        this.vx = Math.cos(heading) * speed
        this.vy = Math.sin(heading) * speed
    }

    update(){
        const {graVal, durVal, ctx, spdVal, radVal} = this
        this.x += this.vx
        this.y += this.vy
        this.vy += graVal
        this.vx *= this.friction
        this.vy *= this.friction
        if(this.dying === false && this.radius < this.futurRadius){
            this.radius += durVal
        }else{
            this.dying = true
        }
        if(this.dying === true){
            this.radius -= durVal
        }
        ctx.save()
        ctx.fillStyle = this.color
        ctx.beginPath()
        // ctx.fillRect(this.x, this.y, this.futurRadius, this.futurRadius)
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
        ctx.closePath()
        ctx.fill()
        ctx.restore()

        if(this.y < 0 || this.radius < 1){
            this.x = this.base[0]
            this.y = this.base[1]
            this.dying = false
            this.radius = 1.1
            this.setSpeed(spdVal)
            this.futurRadius = Math.random() * 3 + radVal
            this.setHeading(Math.random() * 360 / 180 * Math.PI)
        }
    }
}